<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { getAttendancesApi, getAttendancesAdtStatuListApi } from '@/common/apis/attendance';
import type { AttendanceDataList } from '@/common/types/attendance-type'
import { formatDay, getWeekdayText } from '@/common/utils/backg-date-conversion'
import { getLeaderListApi } from '@/common/apis/organization';
import type { SwitchPagination } from '@/common/types/information-type'
import backgMap from '@/common/components/backg-attendance/backg-map.vue';
import backgSetting from '@/common/components/backg-attendance/backg-setting.vue';
import backgWorkdayRecord from '@/common/components/backg-attendance/backg-workday-record.vue';

// 使用一个对象来存储每个复选框的状态
const checked = ref<Record<number, boolean>>({});
// 获取考勤报表数据
const attendancesData = ref();
// 储存部门列表数据
const LeaderDate = ref();
// 储存用户的考勤状态
const statusMap = ref<Record<number, string>>({});
// 按钮间距
const size = ref(10);
// 组件弹框
const attendanceMap = ref();
const modelSetting = ref();
const WorkdayRecord = ref();

// 分页配置
const pagination = reactive({
  page: 1,
  pagesize: 8,
  pageSize: 8, // 每页条数
  total: 0, // 总数据条数
  deptID: [] as number[], // 筛选部门id
});

const columns = ref([
  { title: '序号', dataIndex: 'id', width: 80 },
  { title: '姓名', dataIndex: 'username', width: 130 },
  { title: '工号', dataIndex: 'workNumber', width: 130 },
  { title: '部门', dataIndex: 'departmentName', width: 130 },
  { title: '手机', dataIndex: 'mobile', width: 130 },
]);

// 打卡范围
const atdanceMao = () => {
  attendanceMap.value.showModal();
};

// 考勤设置
const clickSetting = () => {
  modelSetting.value.showModal();
};

// 获取部门数据
const getLeaderListData = async () => {
  const res = await getLeaderListApi();
  LeaderDate.value = res.data.data
};


// 根据 adtStatu 获取样式类名
const getStatusClass = (adtStatu: number) => {
  return `status-${adtStatu}`;
};

// 获取考勤报表数据
const getAttendancesData = async () => {
  // 将 deptID 转换为逗号分隔的字符串
  const deptIDString = pagination.deptID.join(',');
  const res = await getAttendancesApi({
    ...pagination,
    deptID: deptIDString,
  });
  console.log(res, '获取考勤报表数据')
  attendancesData.value = res.data.data.data.rows;
  // 获取分页总条数
  pagination.total = res.data.data.data.total;

  // 动态生成列
  if (attendancesData.value!.length > 0) {
    const firstRecord = attendancesData.value![0];

    // 清空旧列，只保留固定列
    const fixedColumns = columns.value.slice(0, 5); // 假设前 5 列是固定列
    columns.value = fixedColumns;

    // 生成动态列
    const dynamicColumns = firstRecord.attendanceRecord.map((attendance, index) => {
      const weekdayText = getWeekdayText(attendance.day); // 获取六或日
      return {
        title: `${formatDay(attendance.day)}${weekdayText ? `\n${weekdayText}` : ''}`, // 在日期下方显示六或日
        dataIndex: `attendanceRecord_${index}`,
        width: 100,
      };
    });

    // 将动态列追加到 columns 中
    columns.value = [...columns.value, ...dynamicColumns];
  }
};


// 点击筛选
const onCheckbox = (id: number) => {
  checked.value[id] = !checked.value[id];
  // 更新部门筛选数据
  if (checked.value[id]) {
    pagination.deptID.push(id);
  } else {
    const index = pagination.deptID.indexOf(id);
    if (index !== -1) {
      pagination.deptID.splice(index, 1);
    }
  }
  // 重新获取数据
  getAttendancesData()
};


// 获取用户的考勤状态
const getAttendancesAdtStatuListData = async () => {
  const statusData = await getAttendancesAdtStatuListApi();
  statusMap.value = Object.assign({}, ...statusData.data.data);
};

// 根据 adtStatu 获取考勤状态文本
const getStatusText = (adtStatu: number) => {
  return statusMap.value[adtStatu] || '未知'; // 确保键名匹配
};

// 点击分页获取数据
const handleTableChange = async (page: SwitchPagination) => {
  pagination.page = page.current;   // 更新当前页码
  pagination.pagesize = page.pageSize; // 更新当前页码
  await getAttendancesData();
};

// 点击单元格事件
const onclick = async (record: AttendanceDataList, index: number) => {
  const clickedData = record.attendanceRecord[index];
  WorkdayRecord.value.showModal(clickedData);
  await WorkdayRecord.value.getAttendancesAdtStatuListData(clickedData);
};

onMounted(() => {
  getAttendancesData();
  getAttendancesAdtStatuListData();
  getLeaderListData();
});
</script>

<template>
  <div class="attendance">
    <!-- 打卡范围 -->
    <div class="attendance-clockin clockin">
      <div class="attendance-clockin-left">
        <h3>未处理</h3>
        <h2>0</h2>
      </div>
      <a-space :size="size">
        <a-button @click="atdanceMao">打卡范围</a-button>
        <a-button type="primary" @click="clickSetting">设置</a-button>
      </a-space>
    </div>

    <!-- 选择部门 -->
    <div class="attendance-clockin">
      部门：
      <a-checkbox class="attendance-clockin-checkbox" v-for="item in LeaderDate" :key="item.id"
        :checked="checked[item.id]" @click="onCheckbox(item.id)">
        {{ item.name }}
      </a-checkbox>
    </div>

    <!-- 部门成员考勤数据 -->
    <a-table :columns="columns" :pagination="pagination" :data-source="attendancesData" :scroll="{ x: 1500, y: 450 }"
      @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <!-- 动态渲染考勤数据 -->
        <template v-if="column.dataIndex.startsWith('attendanceRecord_')">
          <div @click="onclick(record, column.dataIndex.split('_')[1])"
            :class="getStatusClass(record.attendanceRecord[column.dataIndex.split('_')[1]].adtStatu)">
            {{ getStatusText(record.attendanceRecord[column.dataIndex.split('_')[1]].adtStatu) }}
          </div>
        </template>
      </template>
    </a-table>

    <!-- 打卡范围 -->
    <backgMap ref="attendanceMap" />
    <!-- 出勤设置 -->
    <backgSetting ref="modelSetting" :LeaderDate="LeaderDate" />
    <!-- 实际工作考勤方案 -->
    <backgWorkdayRecord ref="WorkdayRecord" :getAttendancesApiData="getAttendancesApiData" />
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/styles/attendance.scss';

.attendance {
  &-clockin {
    width: 100%;
    height: 100px;
    border-radius: 5px;
    margin-bottom: 10px;
    padding: 20px;
    background-color: rgb(255, 255, 255);

    &-left {
      text-align: center;
    }

    &-checkbox {
      padding: 5px;
    }
  }

  .clockin {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>